﻿
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Xml.Serialization;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// 西图用户app手机调用测试接口
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {        

            string datas = "";
            var ParamIs = new
            {
                name = "LPudding",
                appid = "xtzt"
            };
            var f = HttpUnity.TryGet("http://218.249.198.219/sso/api/usersserviceprovider/isExist", out datas, "post", Encoding.UTF8, new Dictionary<object, object>() {
           // var f = HttpUnity.TryGet("http://localhost:25352/api/usersserviceprovider/isExist", out datas, "post", Encoding.UTF8, new Dictionary<object, object>() {
                     { "requestParam",Newtonsoft.Json.JsonConvert.SerializeObject(ParamIs)}
                });
            string dataquery = "";
            var paramQuery = new
            {
                appid = "xtterminal001",
                name = "",
                userName = "",//读者姓名
                card = "",//读者卡号
                code = "",//证件号码
                rbac = 1,//用户类别
                pageNum = 1,
                pageSize = 27
            };
            f = HttpUnity.TryGet("http://218.249.198.219/sso/api/usersserviceprovider/Query", out dataquery, "post", Encoding.UTF8, new Dictionary<object, object>() {
         // f = HttpUnity.TryGet("http://localhost:25352/api/usersserviceprovider/Query", out dataquery, "post", Encoding.UTF8, new Dictionary<object, object>() {
                { "requestParam",Newtonsoft.Json.JsonConvert.SerializeObject(paramQuery)}
                });
            var s = Newtonsoft.Json.JsonConvert.DeserializeObject(dataquery);
            var ss = Newtonsoft.Json.JsonConvert.DeserializeObject(s.ToString());
            ss = ss;

            #region MyRegion
            //Dictionary<string, string> item = new Dictionary<string, string>()
            //    {
            //        {"name","zlx8wan" },//用户名  必需
            //        {"pass","123456" },//密码  必需
            //        {"nickName","王涛" },//用户 真实姓名   必需
            //        {"eamil","zlx8wan@outlook.com" },//邮箱
            //        {"memo","" },//备注
            //        {"rbac","1" },//是否内部用户 1内部用户 0普通用户	-》图书馆内部用户标识  必需
            //        {"sex","1" },//性别   1男   0女			-》
            //        {"phone","18018983429" },//电话号码	  必需
            //        {"code","622425199002093521" },//身份证  必需
            //        { "card","213123123" },//读者卡  必需
            //        {"area","" },//区县/地区
            //        {"edu","" },//受教育程度
            //        {"pro","" },//职业
            //        {"openid","" },//微信公众号关联 openid
            //    };
            //var item = new
            //{
            //    Name = "zlx8wan",//用户名  必需
            //    pass = "123456",//密码  必需
            //    nickName = "王涛",//用户 真实姓名   必需
            //    eamil = "zlx8wan@outlook.com",//邮箱
            //    memo = "",//备注
            //    rbac = "1",//是否内部用户 1内部用户 0普通用户	-》图书馆内部用户标识  必需
            //    sex = "1",//性别   1男   0女			-》
            //    phone = "18018983429",//电话号码	  必需
            //    code = "622425199002093521",//身份证  必需
            //    card = "213123123",//读者卡  必需
            //    area = "",//区县/地区
            //    edu = "",//受教育程度
            //    pro = "",//职业
            //    openid = "",//微信公众号关联 openid
            //};
            //IList<object> ise = new List<object>();
            //ise.Add(sitem);

            //   f = HttpUnity.TryGet("http://218.249.198.219/sso/api/usersserviceprovider/Add", out dataadd, "post", Encoding.UTF8, new Dictionary<string, string>() {
            //f = HttpUnity.TryGet("http://localhost:25352/api/usersserviceprovider/Add", out dataadd, "post", Encoding.UTF8, new Dictionary<object, object>() {

            //        {"appid","xtzt" },//站点id
            //    {"name","zlx8wan" },
            //    {"tuser",ise  },

            //    }); 
            #endregion
            var parmadd = new
            {
                appid = "xtterminal001",
                count = 1,
                tuser = new List<object>
                {
                    new  {
                          Name="zlx8wan6" ,//用户名  必需
                          pass="e10adc3949ba59abbe56e057f20f883e" ,//密码  必需
                          nickName="王涛" ,//用户 真实姓名   必需
                          email="zlx8wasn@outlook.com" ,//邮箱
                          memo="" ,//备注
                          rbac="1" ,//是否内部用户 1内部用户 0普通用户	-》图书馆内部用户标识  必需
                          sex="1" ,//性别   1男   0女			-》
                          phone="16619864339" ,//电话号码	  必需
                          code="622425199002093521" ,//身份证  必需
                          card="21131123123",//读者卡  必需
                          area="" ,//区县/地区
                          edu="" ,//受教育程度
                          pro="" ,//职业
                          openid="" ,//微信公众号关联 openid
                          islockedcard=true,
                          islockedphone=true,
                          islockedemail=true
                    },
                    // new  {
                    //      Name="zlx8wan3" ,//用户名  必需
                    //      pass="123456" ,//密码  必需
                    //      nickName="王涛" ,//用户 真实姓名   必需
                    //      email="zlx8wan@gamil.com" ,//邮箱
                    //      memo="" ,//备注
                    //      rbac="1" ,//是否内部用户 1内部用户 0普通用户	-》图书馆内部用户标识  必需
                    //      sex="1" ,//性别   1男   0女			-》
                    //      phone="18018983429" ,//电话号码	  必需
                    //      code="622425199002093521" ,//身份证  必需
                    //      card="213123123",//读者卡  必需
                    //      area="" ,//区县/地区
                    //      edu="" ,//受教育程度
                    //      pro="" ,//职业
                    //      openid="" ,//微信公众号关联 openid
                    //}
                }
            };
            string outdataadd = "";
           f = HttpUnity.TryGet("http://218.249.198.219/sso/api/usersserviceprovider/Add", out outdataadd, "post", Encoding.UTF8, new Dictionary<object, object>() {
           // f = HttpUnity.TryGet("http://localhost:25352/api/usersserviceprovider/Add", out outdataadd, "post", Encoding.UTF8, new Dictionary<object, object>() {
                { "requestParam",Newtonsoft.Json.JsonConvert.SerializeObject(parmadd)}
                });
            var ass = Newtonsoft.Json.JsonConvert.DeserializeObject(outdataadd);
            var sae = Newtonsoft.Json.Linq.JObject.Parse(outdataadd);
            foreach (var item in sae)
            {
                var sp = item.Value;
            }
            string datasRemove = "";
            var parmRemove = new
            {
                appid = "xtzt",//站点id
                name = "zlx8wan7"//用户名  必需 
            };
            //f = HttpUnity.TryGet("http://218.249.198.219/sso/api/usersserviceprovider/Remove", out datasRemove, "post", Encoding.UTF8, new Dictionary<object, object>() {
            f = HttpUnity.TryGet("http://localhost:25352/api/usersserviceprovider/Remove", out datasRemove, "post", Encoding.UTF8, new Dictionary<object, object>() {

                   { "requestParam",Newtonsoft.Json.JsonConvert.SerializeObject(parmRemove)}
                });
            string datasUpdate = "";
            var parmUpdata = new
            {
                appid = "xtterminal001",
                count = 2,
                tuser = new List<object>
                {
                    new  {
                        id=21513,//必需的
                          Name="LHarrison" ,//用户名  必需
                          pass="e10adc3949ba59abbe56e057f20f883e" ,//密码  必需
                          nickName="王dasda涛" ,//用户 真实姓名   必需
                          eamil="zlx8wan@outlook.com" ,//邮箱
                          memo="" ,//备注
                          rbac="1" ,//是否内部用户 1内部用户 0普通用户	-》图书馆内部用户标识  必需
                          sex="1" ,//性别   1男   0女			-》
                          phone="18018983425" ,//电话号码	  必需
                          code="622425199002093521" ,//身份证  必需
                          card="2131231123",//读者卡  必需
                          area="" ,//区县/地区
                          edu="" ,//受教育程度
                          pro="" ,//职业
                          openid="" ,//微信公众号关联 openid
                            islockedcard=true,
                          islockedphone=true,
                          islockedemail=true
                    },
                    // new  {
                    //     id=36,
                    //      Name="zlx8wan1" ,//用户名  必需
                    //      pass="123456" ,//密码  必需
                    //      nickName="王涛12" ,//用户 真实姓名   必需
                    //      eamil="zlx8wan@gamil.com" ,//邮箱
                    //      memo="" ,//备注
                    //      rbac="1" ,//是否内部用户 1内部用户 0普通用户	-》图书馆内部用户标识  必需
                    //      sex="1" ,//性别   1男   0女			-》
                    //      phone="18018983429" ,//电话号码	  必需
                    //      code="622425199002093521" ,//身份证  必需
                    //      card="213123123",//读者卡  必需
                    //      area="" ,//区县/地区
                    //      edu="" ,//受教育程度
                    //      pro="" ,//职业
                    //      openid="" ,//微信公众号关联 openid
                    //}
                }
            };
            f = HttpUnity.TryGet("http://218.249.198.219/sso/api/usersserviceprovider/Update", out datasUpdate, "post", Encoding.UTF8, new Dictionary<object, object>() {
           // f = HttpUnity.TryGet("http://localhost:25352/api/usersserviceprovider/Update", out datasUpdate, "post", Encoding.UTF8, new Dictionary<object, object>() {
                 { "requestParam",Newtonsoft.Json.JsonConvert.SerializeObject(parmUpdata)}

                });
            

            ViewBag.Title = "Home Page";

            return View();
        }
        /// <summary>
        /// 西图用户app手机调用测试接口(登陆验证)
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginAuthentication()
        {
            string datas = "";

            var ParamIs = new
            {
                account = "zzap",
                appid = "xtterminal001",
                password= "25f9e794323b453885f5181f1b624d0b"
            };
            var f = HttpUnity.TryGet("http://192.168.1.126//api/usersserviceprovider/Login", out datas, "post", Encoding.UTF8, new Dictionary<object, object>() {
       //  var f = HttpUnity.TryGet("http://218.249.198.219/sso/api/usersserviceprovider/Login", out datas, "post", Encoding.UTF8, new Dictionary<object, object>() {
           // var f = HttpUnity.TryGet("http://localhost:25352/api/usersserviceprovider/Login", out datas, "post", Encoding.UTF8, new Dictionary<object, object>() {
                     { "requestParam",Newtonsoft.Json.JsonConvert.SerializeObject(ParamIs)}
                });
            datas = datas;
            string datasUpdate = "";
            var parmUpdata = new
            {
                appid = "xtterminal001",
                count = 2,
                tuser = new List<object>
                {
                    new  {
                        id=1,//必需的
                          Name="LPudding" ,//用户名  必需
                          pass= "e10adc3949ba59abbe56e057f20f883e" ,//密码  必需
                          nickName="王dasda涛" ,//用户 真实姓名   必需
                          eamil="zlx8wan@outlook.com" ,//邮箱
                          memo="" ,//备注
                          rbac="1" ,//是否内部用户 1内部用户 0普通用户	-》图书馆内部用户标识  必需
                          sex="1" ,//性别   1男   0女			-》
                          phone="16619864399" ,//电话号码	  必需
                          code="622425199002093521" ,//身份证  必需
                          card="2131231123",//读者卡  必需
                          area="" ,//区县/地区
                          edu="" ,//受教育程度
                          pro="" ,//职业
                          openid="" ,//微信公众号关联 openid
                            islockedcard=true,
                          islockedphone=false,
                          islockedemail=true
                    },
                }
            };
           // f = HttpUnity.TryGet("http://218.249.198.219/sso/api/usersserviceprovider/Update", out datasUpdate, "post", Encoding.UTF8, new Dictionary<object, object>() {
            f = HttpUnity.TryGet("http://localhost:25352/api/usersserviceprovider/Update", out datasUpdate, "post", Encoding.UTF8, new Dictionary<object, object>() {
                 { "requestParam",Newtonsoft.Json.JsonConvert.SerializeObject(parmUpdata)}

                });
            return View();
        }

        public ActionResult HeadportraitsUpload()
        {
            return View();
        }
        /// <summary>
        /// 西图用户app手机调用测试接口(头像设置)
        /// </summary>
        /// <returns></returns>
        public ActionResult Headportraits()
        {
            string datas = "";
            byte[] isse = new byte[Request.Files[0].InputStream.Length];
            Request.Files[0].InputStream.Read(isse, 0, isse.Length);
            string base64Str = Convert.ToBase64String(isse);
            base64Str = string.Format("data:{0};base64,{1}", "image/jpeg", base64Str);
            //try
            //{
            //    Stream str = Request.Files[0].InputStream;
            //    System.Drawing.Bitmap bm = new System.Drawing.Bitmap(str);
            //    bm.Save(@"D:\12.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            //}
            //catch (Exception ex)
            //{
            //    throw;
            //}           

            var ParamIss = new
            {
                name = "LPudding",
                appid = "xtterminal001",
                pic= base64Str,
                opType="add"

            };
         // var fs = HttpUnity.TryGet("http://192.168.1.126//api/usersserviceprovider/headportraits", out datas, "post", Encoding.UTF8, new Dictionary<object, object>() {
           var fs = HttpUnity.TryGet("http://218.249.198.219/sso/api/usersserviceprovider/Headportraits", out datas, "post", Encoding.UTF8, new Dictionary<object, object>() {
           // var fs = HttpUnity.TryGet("http://localhost:25352/api/usersserviceprovider/headportraits", out datas, "post", Encoding.UTF8, new Dictionary<object, object>() {
                     { "requestParam",Newtonsoft.Json.JsonConvert.SerializeObject(ParamIss)}
                });

            try
            {
                string s = "";
                if (ParamIss.opType=="add"|| ParamIss.opType == "update" || ParamIss.opType == "query")
                {
                    Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(datas);

                   s = obj["Body"]["sucUser"]["Pic"].ToString();//返回路径
                    ViewBag.sic = base64Str;//上传前
                    ViewBag.pic = s;
                }
                else
                {

                }
               
                return new JsonResult()
                {
                    Data = new
                    {
                        is1 = base64Str,
                        is2 = s
                    }
                };
            }
            catch (Exception ex)
            {
                
            }
            return View("HeadportraitsUpload");
        }
        /// <summary>  
        /// WebClient上传文件至服务器，默认不自动改名  
        /// </summary>  
        /// <param name="fileNamePath">文件名，全路径格式</param>  
        /// <param name="uriString">服务器文件夹路径</param>  
        public void UpLoadFile(string fileNamePath, string uriString)
        {
            UpLoadFile(fileNamePath, uriString, false);
        }
        /// <summary>  
        /// WebClient上传文件至服务器  
        /// </summary>  
        /// <param name="fileNamePath">文件名，全路径格式</param>  
        /// <param name="uriString">服务器文件夹路径</param>  
        /// <param name="IsAutoRename">是否自动按照时间重命名</param>  
        public void UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)
        {
            string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
            string NewFileName = fileName;
            if (IsAutoRename)
            {
                NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));
            }

            string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
            if (uriString.EndsWith("/") == false) uriString = uriString + "/";
            if (!Directory.Exists(uriString))//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(uriString);
            }
            uriString = uriString + NewFileName;
            /**/
            /// 创建WebClient实例  
            System.Net.WebClient myWebClient = new WebClient();

            myWebClient.Credentials = new NetworkCredential("10.1.31.218", "0.");

            // myWebClient.Credentials = CredentialCache.DefaultCredentials;
            // 要上传的文件  
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
            BinaryReader r = new BinaryReader(fs);
            byte[] postArray = r.ReadBytes((int)fs.Length);

            Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
            try
            {
                //使用UploadFile方法可以用下面的格式  
                if (postStream.CanWrite)
                {
                    postStream.Write(postArray, 0, postArray.Length);
                    postStream.Close();
                    fs.Dispose();
                    //  log.AddLog("上传日志文件成功！", "Log");
                    //  basicInfo.writeLogger("上传日志文件成功！" );
                }
                else
                {
                    postStream.Close();
                    fs.Dispose();
                }
            }
            catch (Exception err)
            {
                postStream.Close();
                fs.Dispose();
                throw err;
            }
            finally
            {
                postStream.Close();
                fs.Dispose();
            }
        }

        /// <summary>
        /// 江西中医药门户调用百科信息接口
        /// </summary>
        /// <returns></returns>
        public ActionResult EncyclopediaEntries()
        {
            RestClient client = new RestClient("http://localhost:49398/");
            string result = client.Get("/Home/EncyclopediaEntries");
                Newtonsoft.Json.Linq.JObject ib = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result);


            IList<EntriesJsonModel> entry = new List<EntriesJsonModel>();
            foreach (var item in ib)
            {
                var key = item.Key;
                var value = item.Value;
                if (key=="body")
                {                 
                    var temp = JsonConvert.SerializeObject(value);
                    entry = JsonConvert.DeserializeObject<IList<EntriesJsonModel>>(temp);
                }
            }
            ViewBag.result = result;
            return View(entry);
        }
        /// <summary>
        /// 西图读者借阅历史调用测试接口
        /// </summary>
        /// <returns></returns>
        public ActionResult LoanHistory()
        {
            var datas = "";
            var ParamIss = new
            {
                readerCard = "000400026688"

            };
          //  http://localhost:25352/UserCenter/LoanHistory/?readerCard=000400026688
            // var fs = HttpUnity.TryGet(" http://localhost:25352/UserCenter/LoanHistory", out datas, "post", Encoding.UTF8, new Dictionary<object, object>() {
           var fs = HttpUnity.TryGet("http://218.249.198.219/sso/UserCenter/LoanHistory", out datas, "post", Encoding.UTF8, new Dictionary<object, object>() {
          // var fs = HttpUnity.TryGet(" http://localhost:25352/UserCenter/LoanHistory", out datas, "post", Encoding.UTF8, new Dictionary<object, object>() {
                     { "requestParam",Newtonsoft.Json.JsonConvert.SerializeObject(ParamIss)}
                });

            return View();
        }
        /// <summary>
        /// 江西中医药门户调用知识地图接口测试
        /// </summary>
        /// <returns></returns>
        public ActionResult JX_MH_ZSDT()
        {
            return View();
        }
        /// <summary>
        /// 江西中医药知识地图
        /// </summary>
        /// <returns></returns>
        public ActionResult JXZSDT()
        {
            return View();
        }
        /// <summary>
        /// 江西中医药知识地图详情
        /// </summary>
        /// <returns></returns>
        public ActionResult JXZSDT_Details()
        {
            return View();
        }
        public ActionResult agent()
        {
            return View();
        }
    }
    public class RestClient
    {
        private string BaseUri;
        public RestClient(string baseUri)
        {
            this.BaseUri = baseUri;
        }

        #region Get请求
        public string Get(string uri)
        {
            //先根据用户请求的uri构造请求地址
            string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
            //创建Web访问对  象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //通过Web访问对象获取响应内容
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
            string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
            reader.Close();
            myResponse.Close();
            return returnXml;
        }
        #endregion

        #region Post请求
        public string Post(string data, string uri)
        {
            //先根据用户请求的uri构造请求地址
            string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
            //创建Web访问对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //把用户传过来的数据转成“UTF-8”的字节流
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);

            myRequest.Method = "POST";
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "application/json";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;
            //发送请求
            Stream stream = myRequest.GetRequestStream();
            stream.Write(buf, 0, buf.Length);
            stream.Close();

            //获取接口返回值
            //通过Web访问对象获取响应内容
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
            string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
            reader.Close();
            myResponse.Close();
            return returnXml;

        }
        #endregion

        #region Put请求
        public string Put(string data, string uri)
        {
            //先根据用户请求的uri构造请求地址
            string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
            //创建Web访问对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //把用户传过来的数据转成“UTF-8”的字节流
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);

            myRequest.Method = "PUT";
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "application/json";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;
            //发送请求
            Stream stream = myRequest.GetRequestStream();
            stream.Write(buf, 0, buf.Length);
            stream.Close();

            //获取接口返回值
            //通过Web访问对象获取响应内容
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
            string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
            reader.Close();
            myResponse.Close();
            return returnXml;

        }
        #endregion


        #region Delete请求
        public string Delete(string data, string uri)
        {
            //先根据用户请求的uri构造请求地址
            string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
            //创建Web访问对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //把用户传过来的数据转成“UTF-8”的字节流
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);

            myRequest.Method = "DELETE";
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "application/json";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;
            //发送请求
            Stream stream = myRequest.GetRequestStream();
            stream.Write(buf, 0, buf.Length);
            stream.Close();

            //获取接口返回值
            //通过Web访问对象获取响应内容
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
            string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
            reader.Close();
            myResponse.Close();
            return returnXml;

        }
        #endregion
    }
    public static class HttpUnity
    {
        public static bool TryGet(string url, out string data, string method = "GET", Encoding encoding = null, Dictionary<object, object> parameters = null, Action<HttpWebRequest> deleagate = null)
        {
            HttpWebRequest request = (HttpWebRequest)null;
            HttpWebResponse httpWebResponse = (HttpWebResponse)null;
            try
            {
                if (string.Compare(method, "GET", true) == 0)
                    url = HttpUnity.CombineUrl(url, parameters);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = method;
                if (string.Compare(method, "POST", true) == 0)
                    HttpUnity.AppendPostParameters(request, parameters);
                if (deleagate != null)
                    deleagate(request);
                httpWebResponse = (HttpWebResponse)request.GetResponse();
                data = HttpUnity.GetResponseText((WebResponse)httpWebResponse, encoding);
                return true;
            }
            catch (WebException ex)
            {
                data = HttpUnity.GetResponseText(ex.Response, encoding);
                return false;
            }
            finally
            {
                if (request != null)
                    ;
                if (httpWebResponse != null)
                    httpWebResponse.Close();
            }
        }

        private static string CombineUrl(string url, Dictionary<object, object> data)
        {
            if (data == null || data.Count == 0)
                return url;
            string empty = string.Empty;
            foreach (KeyValuePair<object, object> keyValuePair in data)
            {
                //   if (!string.IsNullOrEmpty(keyValuePair.Value))
                if (keyValuePair.Value != null)
                    empty += string.Format("&{0}={1}", (object)keyValuePair.Key, keyValuePair.Value);
                // empty += string.Format("&{0}={1}", (object)keyValuePair.Key, (object)Uri.EscapeDataString(keyValuePair.Value));
            }
            if (empty.Length <= 0)
                return url;
            if (url.IndexOf('?') == -1)
                return url + "?" + empty.Substring(1);
            return url + empty;
        }

        private static string GetResponseText(WebResponse response, Encoding encoding = null)
        {
            Stream responseStream;
            if (response == null || (responseStream = response.GetResponseStream()) == null)
                return string.Empty;
            MemoryStream memoryStream = new MemoryStream();
            BinaryReader binaryReader = new BinaryReader(responseStream);
            int count1 = 1024;
            byte[] buffer = new byte[count1];
            int count2;
            while ((count2 = binaryReader.Read(buffer, 0, count1)) > 0)
                memoryStream.Write(buffer, 0, count2);
            byte[] numArray = memoryStream.ToArray();
            string str = response.Headers == null ? (string)null : response.Headers["Content-encoding"];
            if (str != null && str.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
                numArray = Utils.UnZip(numArray);
            if (encoding == null)
                encoding = Encoding.UTF8;
            return encoding.GetString(numArray);
        }

        private static void AppendPostParameters(HttpWebRequest request, Dictionary<object, object> data)
        {
            if (data == null || data.Count == 0)
                return;
            StringBuilder stringBuilder = new StringBuilder();
            foreach (KeyValuePair<object, object> keyValuePair in data)
                //  stringBuilder.AppendFormat("&{0}={1}", (object)keyValuePair.Key, (object)Uri.EscapeDataString(keyValuePair.Value));
                stringBuilder.AppendFormat("&{0}={1}", (object)keyValuePair.Key, (object)keyValuePair.Value);
            stringBuilder.Remove(0, 1);
            byte[] bytes = Encoding.UTF8.GetBytes(stringBuilder.ToString());
            request.ContentLength = (long)bytes.Length;
            request.ContentType = "application/x-www-form-urlencoded";
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
        }
    }
    public static class Utils
    {
        private static bool RegeX(object obj, string pattern)
        {
            if (obj == null)
                return false;
            try
            {
                if (Regex.IsMatch(obj.ToString(), pattern))
                    return true;
            }
            catch
            {
            }
            return false;
        }

        public static bool IsInteger(object obj)
        {
            return Utils.RegeX(obj, "^\\d+$");
        }

        public static bool IsName(object obj)
        {
            return Utils.RegeX(obj, "^\\w{2,40}$");
        }

        public static bool IsEmail(object obj)
        {
            return Utils.RegeX(obj, "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
        }

        public static bool IsIPAddress(object obj)
        {
            return Utils.RegeX(obj, "^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$");
        }

        public static bool IsUrl(object obj)
        {
            return Utils.RegeX(obj, "^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$");
        }

        public static bool Serializer<T>(T t, string filename)
        {
            using (FileStream fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
                new XmlSerializer(typeof(T)).Serialize((Stream)fileStream, (object)t);
            return true;
        }

        public static T Deserialize<T>(string filename)
        {
            using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
                return (T)new XmlSerializer(typeof(T)).Deserialize((Stream)fileStream);
        }

        public static string XmlSerializer<T>(T t)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                new XmlSerializer(typeof(T)).Serialize((Stream)memoryStream, (object)t);
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
        }

        public static T XmlDeserialize<T>(string text)
        {
            using (MemoryStream memoryStream = new MemoryStream(Encoding.Default.GetBytes(text)))
                return (T)new XmlSerializer(typeof(T), "").Deserialize((Stream)memoryStream);
        }

        public static string JsonSerializer<T>(T t)
        {
            return new JavaScriptSerializer().Serialize((object)t);
        }

        public static T JsonDeserialize<T>(string input)
        {
            return new JavaScriptSerializer().Deserialize<T>(input);
        }

        public static string XmlDataSerializer<T>(T t)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                new DataContractSerializer(typeof(T)).WriteObject((Stream)memoryStream, (object)t);
                return Encoding.UTF8.GetString(memoryStream.GetBuffer());
            }
        }

        public static T XmlDataDeserialize<T>(string text)
        {
            using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(text)))
                return (T)new DataContractSerializer(typeof(T)).ReadObject((Stream)memoryStream);
        }

        public static string JsonDataSerializer<T>(T t)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                new DataContractJsonSerializer(typeof(T)).WriteObject((Stream)memoryStream, (object)t);
                return Encoding.UTF8.GetString(memoryStream.GetBuffer());
            }
        }

        public static T JsonDataDeserialize<T>(string text)
        {
            using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(text)))
                return (T)new DataContractJsonSerializer(typeof(T)).ReadObject((Stream)memoryStream);
        }

        public static void WriteEventLog(string source, string message, EventLogEntryType type)
        {
            try
            {
                EventLog.WriteEntry(source, message, type);
            }
            catch
            {
            }
        }

        public static void WriteFileLog(string logfile, string message, EventLogEntryType type = EventLogEntryType.Information)
        {
            lock (typeof(Utils))
            {
                StreamWriter streamWriter = new StreamWriter(logfile, true, Encoding.UTF8);
                streamWriter.WriteLine(string.Format("{0} {1} {2}", (object)DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), (object)type, (object)message));
                streamWriter.Close();
            }
        }

        public static void WriteFileLog(string message)
        {
            try
            {
                string str = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LogFiles");
                string path2 = DateTime.Now.ToString("yyyyMMdd") + ".log";
                if (!Directory.Exists(str))
                    return;
                Utils.WriteFileLog(Path.Combine(str, path2), message, EventLogEntryType.Information);
            }
            catch
            {
            }
        }

        private static ushort Makeword(byte bLow, byte bHigh)
        {
            return (ushort)((uint)bLow | (uint)bHigh << 8);
        }

        private static uint Makelong(ushort bLow, ushort bHigh)
        {
            return (uint)bLow | (uint)bHigh << 16;
        }

        public static uint IPToNum(string IPAddr)
        {
            string[] strArray1 = new string[4];
            string[] strArray2 = IPAddr.Split('.');
            return Utils.Makelong(Utils.Makeword(byte.Parse(strArray2[3]), byte.Parse(strArray2[2])), Utils.Makeword(byte.Parse(strArray2[1]), byte.Parse(strArray2[0])));
        }

        public static string NumToIP(uint ipnum)
        {
            int num1 = (int)(ipnum % 256U);
            ipnum = (uint)(((ulong)ipnum - (ulong)num1) / 256UL);
            int num2 = (int)(ipnum % 256U);
            ipnum = (uint)(((ulong)ipnum - (ulong)num2) / 256UL);
            int num3 = (int)(ipnum % 256U);
            ipnum = (uint)(((ulong)ipnum - (ulong)num3) / 256UL);
            return ((int)ipnum).ToString() + "." + num3.ToString() + "." + num2.ToString() + "." + num1.ToString();
        }

        public static T FactoryCreator<T>(string providerPath, string providerName, params object[] args)
        {
            object data = AppDomain.CurrentDomain.GetData(providerName);
            if (data == null)
            {
                data = Assembly.Load(providerPath).CreateInstance(providerName, true, BindingFlags.Default, (Binder)null, args, (CultureInfo)null, (object[])null);
                AppDomain.CurrentDomain.SetData(providerName, data);
            }
            return (T)data;
        }

        public static T ChannelCreator<T>(string endpoint)
        {
            object data = AppDomain.CurrentDomain.GetData(endpoint);
            if (data == null)
            {
                data = (object)ChannelFactory<T>.CreateChannel((Binding)new NetTcpBinding(SecurityMode.None), new EndpointAddress(endpoint));
                AppDomain.CurrentDomain.SetData(endpoint, data);
            }
            return (T)data;
        }

        public static T ChannelCreator<T>(Binding binding, EndpointAddress endpoint)
        {
            string absoluteUri = endpoint.Uri.AbsoluteUri;
            object data = AppDomain.CurrentDomain.GetData(absoluteUri);
            if (data == null)
            {
                data = (object)ChannelFactory<T>.CreateChannel(binding, endpoint);
                AppDomain.CurrentDomain.SetData(absoluteUri, data);
            }
            return (T)data;
        }

        public static Func<object> CreateInstance(this System.Type type)
        {
            return ((Expression<Func<object>>)(() => Expression.New(type))).Compile();
        }

        public static Func<T, object> CreateInstance<T>(this System.Type type)
        {
            System.Type type1 = typeof(T);
            ConstructorInfo constructor = type.GetConstructor(new System.Type[1]
            {
        type1
            });
            ParameterExpression[] parameterExpressionArray = new ParameterExpression[1]
            {
        System.Linq.Expressions.Expression.Parameter(type1, "arg")
            };
            return System.Linq.Expressions.Expression.Lambda<Func<T, object>>((Expression)Expression.New(constructor, (Expression[])parameterExpressionArray), parameterExpressionArray).Compile();
        }

        public static byte[] Zip(byte[] data)
        {
            MemoryStream memoryStream = new MemoryStream();
            GZipStream gzipStream = new GZipStream((Stream)memoryStream, CompressionMode.Compress);
            BinaryWriter binaryWriter = new BinaryWriter((Stream)gzipStream);
            binaryWriter.Write(data);
            binaryWriter.Close();
            gzipStream.Close();
            byte[] array = memoryStream.ToArray();
            memoryStream.Close();
            return array;
        }

        public static byte[] UnZip(byte[] data)
        {
            MemoryStream memoryStream1 = new MemoryStream(data);
            GZipStream gzipStream = new GZipStream((Stream)memoryStream1, CompressionMode.Decompress);
            StreamReader streamReader = new StreamReader((Stream)gzipStream);
            int count1 = 1024;
            byte[] buffer = new byte[count1];
            MemoryStream memoryStream2 = new MemoryStream();
            int count2;
            while ((count2 = streamReader.BaseStream.Read(buffer, 0, count1)) > 0)
                memoryStream2.Write(buffer, 0, count2);
            memoryStream1.Close();
            gzipStream.Close();
            streamReader.Close();
            return memoryStream2.ToArray();
        }
    }
    public class EntriesJsonModel
    {
        public string ClassifyName { get; set; }
        public IList<Entry> Entries { get; set; }
    }
    public class Entry
    {
        /// <summary>
        /// 标题
        /// </summary>
        public string BasicTitle { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string BasicContent { get; set; }
        /// <summary>
        /// 图片
        /// </summary>
        public string Imag { get; set; }
        public DateTime ModifyTime { set; get; }
        /// <summary>
        /// 链接(例如'/Home/QueryByEntry/?query="王松"')
        /// </summary>
        public string Link { get; set; }
        /// <summary>
        /// 相关词条
        /// </summary>
        public IList<Rel> RelEntries { get; set; }
    }
    /// <summary>
    /// 相关词条
    /// </summary>
    public class Rel
    {
        /// <summary>
        /// 标题
        /// </summary>
        public string BasicTitle { get; set; }
        /// <summary>
        /// 链接(例如'/Home/QueryByEntry/?query="王松"')
        /// </summary>
        public string Link { get; set; }
    }

}


